package cn.john.hrm.service;

import cn.john.hrm.domain.LoginUser;
import cn.john.hrm.domain.Permission;
import cn.john.hrm.mapper.LoginUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 获取数据库中的用户信息
 * 通过username  最终还是要交给spring管理
 */
@Service
public class MySecurityService implements UserDetailsService{
    @Autowired
    private LoginUserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(username);
        // 通过用户名从数据库中查询出用户信息
        LoginUser user = userMapper.selectOne(loginUser);
        if (user == null)
            throw new RuntimeException("对不起，没有该用户!!!!");
        // 用户存在 查询用户的权限
        List<Permission> userPers = userMapper.getUserPermissionsById(user.getId());
        ArrayList<GrantedAuthority> permissions = new ArrayList<>();
        // 将查询出来的用户权限交给security管理
        userPers.stream().forEach(permission -> {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission.getSn());
            permissions.add(authority);
        });
        return new User(user.getUsername(),user.getPassword(),permissions);
    }

    /*public static void main(String[] args) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String pwd = "1";
        String encodePwd = encoder.encode(pwd);
        System.out.println(encodePwd);
        boolean matches = encoder.matches(pwd, encodePwd);
        System.out.println(matches);
    }*/
}
